package com.qili.controller.supervisor;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.qili.core.utils.DictTypes;
import com.qili.entity.jc.dto.JcProjectDTO;
import com.qili.entity.supervisor.dto.SupervisorProjectDTO;
import com.qili.entity.base.BaseDict;
import com.qili.entity.sys.SysRegion;
import com.qili.entity.sys.SysRole;
import com.qili.entity.zx.dto.ZxProjectDTO;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.StatisticsService;
import com.qili.service.supervisor.SupervisorProjectService;
import com.qili.service.sys.RoleService;
import com.qili.service.sys.SysRegionService;
import com.qili.util.BeanUtil;
import com.qili.util.CommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/*
* @Author:qiguoqing
* @Description 数据统计
* @Date:2020/11/9
*/
@Controller
@Slf4j
@RequestMapping("/sys/statistics")
public class StatisticsController {

    @Autowired
    SupervisorProjectService supervisorProjectService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    StatisticsService statisticsService;
    @Autowired
    SysRegionService sysRegionService;
    @Autowired
    private RoleService roleService;


    @GetMapping(value = "mydata")
    public String index(Model model) {
        //获取项目类型
        List<BaseDict> BTlist = baseDictService.selectByTypeCode(DictTypes.YW_TYPE.getType());
        //获取行业类型
        List<BaseDict> HYlist = baseDictService.selectByTypeCode(DictTypes.INDUSTRY.getType());
        //获取监理项目角色
        SysRole sr = new SysRole();
        sr.setNote("proj");
        List<SysRole> projectRoleList = roleService.select(sr);
        //获取咨询项目角色
        SysRole zx = new SysRole();
        zx.setNote("proZx");
        projectRoleList.addAll(roleService.select(zx));
        //获取检测项目角色
        SysRole jc = new SysRole();
        jc.setNote("proJc");
        projectRoleList.addAll(roleService.select(jc));
        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");
        // 市
//        List<SysRegion> citylist = sysRegionService.selectListByLevelId("2");
        model.addAttribute("provincelist", provincelist);
//        model.addAttribute("citylist", citylist);
        model.addAttribute("BTlist", BTlist);
        model.addAttribute("HYlist", HYlist);
        model.addAttribute("projectRoleList", projectRoleList);
        return "/statistics/myData";
    }
    @GetMapping(value = "mydata2")
    public String index2(Model model, HttpServletRequest request) {
        String  jztype=request.getParameter("jztype");
        if("002".equals(jztype)){
            //从项目main 页面 frame 加载
            model.addAttribute("jztype", jztype);
        }


        List<BaseDict> BTlist = baseDictService.selectByTypeCode("BT001");
        model.addAttribute("BTlist", BTlist);
        return "/statistics/myData2";
    }

    @ApiOperation(value = "/showProjectList", httpMethod = "GET", notes = "项目统计")
    @GetMapping(value = "showProjectList")
    @ResponseBody
   public List selectNumber(SupervisorProjectDTO supervisorProjectDto, Model model, String page, String limit) {
        String userId = CommonUtil.getUserId();
        List<JSONObject> tableData = new ArrayList<>();
        //查询个人监理项目 001 监理；002 咨询；003 检测
        if("001".equals(supervisorProjectDto.getProjectType())){
            tableData = this.jl(supervisorProjectDto, userId);
        }else if("002".equals(supervisorProjectDto.getProjectType())){
            tableData = this.zx(supervisorProjectDto, userId);
        }else if("003".equals(supervisorProjectDto.getProjectType())){
            tableData = this.jc(supervisorProjectDto,userId);
        }else {
            // 计算 监理 检测 咨询的总和
            List<JSONObject> jl = this.jl(supervisorProjectDto, userId);
            List<JSONObject> zx = this.zx(supervisorProjectDto, userId);
            List<JSONObject> jc = this.jc(supervisorProjectDto, userId);
            // 项目个数为
            tableData.add(new JSONObject().append("subject","项目个数").append("data",new BigDecimal(subStringqh(jl.get(0).get("data"))).add(new BigDecimal(subStringqh(zx.get(0).get("data"))).add(new BigDecimal(subStringqh(jc.get(0).get("data")))))));

            // 服务费最大值
            Integer fwfjl = Integer.parseInt(subStringqh(jl.get(1).get("data").toString()));
            Integer fwfzx = Integer.parseInt(subStringqh(zx.get(1).get("data").toString()));
            Integer fwfjc = Integer.parseInt(subStringqh(jc.get(1).get("data").toString()));
            fwfjl = (fwfjl>fwfzx?fwfjl:fwfzx)>fwfjc?(fwfjl>fwfzx?fwfjl:fwfzx):fwfjc;// 获取最大值
            tableData.add(new JSONObject().append("subject","服务费最大值(元)").append("data",fwfjl));

            // 投资额最大值
            Integer tzejl = Integer.parseInt(subStringqh(jl.get(2).get("data").toString()));
            Integer tzezx = Integer.parseInt(subStringqh(zx.get(2).get("data").toString()));
            Integer tzejc = Integer.parseInt(subStringqh(jc.get(2).get("data").toString()));
            tzejl = (tzejl>tzezx?tzejl:tzezx)>tzejc?(tzejl>tzezx?tzejl:tzezx):tzejc;
            tableData.add(new JSONObject().append("subject","投资额最大值(元)").append("data",tzejl));

            // 服务费总计(元)
            BigDecimal fwfz = new BigDecimal(subStringqh(jl.get(3).get("data"))).add(new BigDecimal(subStringqh(zx.get(3).get("data")))).add(new BigDecimal(subStringqh(jc.get(3).get("data"))));
            tableData.add(new JSONObject().append("subject","服务费总计(元)").append("data",fwfz.setScale(2,BigDecimal.ROUND_HALF_UP)));

            // 投资额总计
            BigDecimal tzez = new BigDecimal(subStringqh(jl.get(4).get("data"))).add(new BigDecimal(subStringqh(zx.get(4).get("data")))).add(new BigDecimal(subStringqh(jc.get(4).get("data"))));
            tableData.add(new JSONObject().append("subject","投资额总计(元)").append("data",tzez.setScale(2,BigDecimal.ROUND_HALF_UP)));
        }
        return tableData;
    }

    /**
     * 监理
     * @param supervisorProjectDto
     * @return
     */
    private List<JSONObject> jl(SupervisorProjectDTO supervisorProjectDto, String userId){
        supervisorProjectDto.setDestatus("000");//  查询不是删除状态的项目
        supervisorProjectDto.setUserId(userId);
        statisticsService.format(supervisorProjectDto);
        return getTableData(statisticsService.selectNumber(supervisorProjectDto));
    }

    /**
     * 咨询
     * @param supervisorProjectDto
     * @return
     */
    private List<JSONObject> zx(SupervisorProjectDTO supervisorProjectDto, String userId){
        //查询个人咨询项目
        ZxProjectDTO zxProjectDTO = new ZxProjectDTO();
        zxProjectDTO.setDestatus("000");
        zxProjectDTO.setUserId(userId);
        // copy 查询条件
        BeanUtil.copyNotNullBean(supervisorProjectDto,zxProjectDTO);
        statisticsService.format(zxProjectDTO);
        return getTableDataZx(statisticsService.selectNumber(zxProjectDTO));
    }

    /**
     * 检测
     * @param supervisorProjectDto
     * @return
     */
    private List<JSONObject> jc(SupervisorProjectDTO supervisorProjectDto, String userId){
        //查询个人检测项目
        JcProjectDTO jcProjectDTO = new JcProjectDTO();
        jcProjectDTO.setDestatus("000");
        jcProjectDTO.setUserId(userId);
        BeanUtil.copyNotNullBean(supervisorProjectDto,jcProjectDTO);
        statisticsService.format(jcProjectDTO);
        return getTableDataJc(statisticsService.selectNumber(jcProjectDTO));
    }

    /**
     * 监理
     * 计算服务费最大值,投资额最大值,服务费总计,投资额总计
     * @param dtoList
     * @return
     */
    List<JSONObject> getTableData(List<SupervisorProjectDTO> dtoList){
        List<JSONObject> jsonObjectList = new ArrayList<JSONObject>();
        //服务费总计
        BigDecimal fwTotal = BigDecimal.ZERO;
        //投资额总计
        BigDecimal tzTotal = BigDecimal.ZERO;
        //服务费最大值
        BigDecimal fwMax = BigDecimal.ZERO;
        //投资额最大值
        BigDecimal tzMax = BigDecimal.ZERO;
        if(CollectionUtil.isNotEmpty(dtoList)){
            for(SupervisorProjectDTO dto : dtoList){
                if(StringUtils.isNotBlank(dto.getHtMoney())){
                    //加服务费
                    fwTotal = fwTotal.add(new BigDecimal(dto.getHtMoney()));
                    //比较大小
                    fwMax = fwMax.compareTo(new BigDecimal(dto.getHtMoney())) == -1 ? new BigDecimal(dto.getHtMoney()) : fwMax;
                }
                if(StringUtils.isNotBlank(dto.getTzMoney())){
                    //加投资额
                    tzTotal = tzTotal.add(new BigDecimal(dto.getTzMoney()));
                    //比较大小
                    tzMax = tzMax.compareTo(new BigDecimal(dto.getTzMoney())) == -1 ? new BigDecimal(dto.getTzMoney()) : tzMax;
                }
            }
        }
        jsonObjectList.add(new JSONObject().append("subject","项目个数").append("data",dtoList.size()));
        jsonObjectList.add(new JSONObject().append("subject","服务费最大值(元)").append("data",fwMax.setScale(2,BigDecimal.ROUND_HALF_UP)));
        jsonObjectList.add(new JSONObject().append("subject","投资额最大值(元)").append("data",tzMax.setScale(2,BigDecimal.ROUND_HALF_UP)));
        jsonObjectList.add(new JSONObject().append("subject","服务费总计(元)").append("data",fwTotal.setScale(2,BigDecimal.ROUND_HALF_UP)));
        jsonObjectList.add(new JSONObject().append("subject","投资额总计(元)").append("data",tzTotal.setScale(2,BigDecimal.ROUND_HALF_UP)));
        return jsonObjectList;
    }

    /**
     * 咨询
     * 计算服务费最大值,投资额最大值,服务费总计,投资额总计
     * @param dtoList
     * @return
     */
    List<JSONObject> getTableDataZx(List<ZxProjectDTO> dtoList){
        List<JSONObject> jsonObjectList = new ArrayList<JSONObject>();
        //服务费总计
        BigDecimal fwTotal = BigDecimal.ZERO;
        //投资额总计
        BigDecimal tzTotal = BigDecimal.ZERO;
        //服务费最大值
        BigDecimal fwMax = BigDecimal.ZERO;
        //投资额最大值
        BigDecimal tzMax = BigDecimal.ZERO;
        if(CollectionUtil.isNotEmpty(dtoList)){
            for(ZxProjectDTO dto : dtoList){
                if(StringUtils.isNotBlank(dto.getHtMoney())){
                    //加服务费
                    fwTotal = fwTotal.add(new BigDecimal(dto.getHtMoney()));
                    //比较大小
                    fwMax = fwMax.compareTo(new BigDecimal(dto.getHtMoney())) == -1 ? new BigDecimal(dto.getHtMoney()) : fwMax;
                }
                if(StringUtils.isNotBlank(dto.getTzMoney())){
                    //加投资额
                    tzTotal = tzTotal.add(new BigDecimal(dto.getTzMoney()));
                    //比较大小
                    tzMax = tzMax.compareTo(new BigDecimal(dto.getTzMoney())) == -1 ? new BigDecimal(dto.getTzMoney()) : tzMax;
                }
            }
        }
        jsonObjectList.add(new JSONObject().append("subject","项目个数").append("data",dtoList.size()));
        jsonObjectList.add(new JSONObject().append("subject","服务费最大值(元)").append("data",fwMax.setScale(2,BigDecimal.ROUND_HALF_UP)));
        jsonObjectList.add(new JSONObject().append("subject","投资额最大值(元)").append("data",tzMax.setScale(2,BigDecimal.ROUND_HALF_UP)));
        jsonObjectList.add(new JSONObject().append("subject","服务费总计(元)").append("data",fwTotal.setScale(2,BigDecimal.ROUND_HALF_UP)));
        jsonObjectList.add(new JSONObject().append("subject","投资额总计(元)").append("data",tzTotal.setScale(2,BigDecimal.ROUND_HALF_UP)));
        return jsonObjectList;
    }

    /**
     * 检测
     * 计算服务费最大值,投资额最大值,服务费总计,投资额总计
     * @param dtoList
     * @return
     */
    List<JSONObject> getTableDataJc(List<JcProjectDTO> dtoList){
        List<JSONObject> jsonObjectList = new ArrayList<JSONObject>();
        //服务费总计
        BigDecimal fwTotal = BigDecimal.ZERO;
        //投资额总计
        BigDecimal tzTotal = BigDecimal.ZERO;
        //服务费最大值
        BigDecimal fwMax = BigDecimal.ZERO;
        //投资额最大值
        BigDecimal tzMax = BigDecimal.ZERO;
        if(CollectionUtil.isNotEmpty(dtoList)){
            for(JcProjectDTO dto : dtoList){
                if(StringUtils.isNotBlank(dto.getHtMoney())){
                    //加服务费
                    fwTotal = fwTotal.add(new BigDecimal(dto.getHtMoney()));
                    //比较大小
                    fwMax = fwMax.compareTo(new BigDecimal(dto.getHtMoney())) == -1 ? new BigDecimal(dto.getHtMoney()) : fwMax;
                }
                if(StringUtils.isNotBlank(dto.getTzMoney())){
                    //加投资额
                    tzTotal = tzTotal.add(new BigDecimal(dto.getTzMoney()));
                    //比较大小
                    tzMax = tzMax.compareTo(new BigDecimal(dto.getTzMoney())) == -1 ? new BigDecimal(dto.getTzMoney()) : tzMax;
                }
            }
        }
        jsonObjectList.add(new JSONObject().append("subject","项目个数").append("data",dtoList.size()));
        jsonObjectList.add(new JSONObject().append("subject","服务费最大值(元)").append("data",fwMax.setScale(2,BigDecimal.ROUND_HALF_UP)));
        jsonObjectList.add(new JSONObject().append("subject","投资额最大值(元)").append("data",tzMax.setScale(2,BigDecimal.ROUND_HALF_UP)));
        jsonObjectList.add(new JSONObject().append("subject","服务费总计(元)").append("data",fwTotal.setScale(2,BigDecimal.ROUND_HALF_UP)));
        jsonObjectList.add(new JSONObject().append("subject","投资额总计(元)").append("data",tzTotal.setScale(2,BigDecimal.ROUND_HALF_UP)));
        return jsonObjectList;
    }

    /**
     * 把Object 转为 BigDecimal
     * @param value
     * @return
     */
    public static BigDecimal getBigDecimal(Object value) {
        BigDecimal ret = null;
        if (value != null) {
            if (value instanceof BigDecimal) {
                ret = (BigDecimal) value;
            } else if (value instanceof String) {
                ret = new BigDecimal((String) value);
            } else if (value instanceof BigInteger) {
                ret = new BigDecimal((BigInteger) value);
            } else if (value instanceof Number) {
                ret = new BigDecimal(((Number) value).doubleValue());
            } else {
                throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
            }
        }
        return ret;
    }

    /**
     * 取出来的数据： [24]
     * 使用字符串把两边符号去掉
     * @param o
     * @return
     */
    private String subStringqh(Object o){
        String str = o.toString();
        String substring = str.substring(1, str.length() - 1);
        return substring;
    }


}
